package scoreCard.LivestockJudging3C;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import org.json.JSONArray;

import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Util;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

import scoreCard.LivestockJudging3C.R;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class CommentActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share);

		Bundle info = getIntent().getExtras();
		if (info != null) {
			id=info.getString("ID");
		}
		
		mPrefs = getPreferences(MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);
		if (access_token != null) {
			facebook.setAccessToken(access_token);
		}
		if (expires != 0) {
			facebook.setAccessExpires(expires);
		}

		if (!facebook.isSessionValid()) {
			facebook.authorize(this, new String[] { "publish_stream" },
					new DialogListener() {
						public void onComplete(Bundle values) {
							SharedPreferences.Editor editor = mPrefs.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
						}

						public void onFacebookError(FacebookError error) {
						}

						public void onError(DialogError e) {
						}

						public void onCancel() {
						}
					});
		}
		postListView = (ListView) this.findViewById(R.id.postListView);
		allComments = new ArrayList<FacebookPost>();
		// All four methods work
		getCommentsOnPost(id);
		
		final EditText posttext = (EditText)findViewById(R.id.facebookPost);
		posttext.setHint("Enter Comment");
		final Button postButton = (Button)findViewById(R.id.postButton);
		postButton.setText("Comment");

		aa = new PostAdapter(this, R.layout.postlayout, this.allComments);
		postListView.setAdapter(this.aa);
		postButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				if(!posttext.getText().toString().equals("")){
					commentOnPost(id,posttext.getText().toString());
					posttext.setText("");
					getCommentsOnPost(id);
				}
			}
		});
		
		final TextView moreText = (TextView)findViewById(R.id.moreButton);
		moreText.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				numPosts += 5;
				getCommentsOnPost(id);
				aa.notifyDataSetChanged();
			}
		});
		
		//postToPage("Posting from the 3C Livestock Judging Android App");
		//commentOnPost("344347108936890_344502358921365", "Thanks! We can now comment on posts from the app too!");
	}
	
	private void setAdapter() {
		aa = new PostAdapter(this, R.layout.postlayout, this.allComments);
		postListView.setAdapter(aa);
		aa.notifyDataSetChanged();
	}
	
	public void onResume() {
		super.onResume();
		facebook.extendAccessTokenIfNeeded(this, null);
		Bundle info = getIntent().getExtras();
		if (info != null) {
			id=info.getString("ID");
		}
		getCommentsOnPost(id);
		setAdapter();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		facebook.authorizeCallback(requestCode, resultCode, data);
	}

	private void commentOnPost(String postID, String message) {
		Bundle bundle = new Bundle();
		bundle.putString("message", message);
		bundle.putString(Facebook.TOKEN, facebook.getAccessToken());
		mAsyncRunner.request(postID + "/comments", bundle, "POST",
				new PostRequestListener(), "Comment");
	}
	
	private void getCommentsOnPost(String postID) {
		allComments.clear();
		JSONObject feed;
		try {
			feed = Util.parseJson(facebook.request("3CLivestockJudging/feed"));
			JSONArray dataArray = feed.getJSONArray("data");
			for (int i = 0; i < dataArray.length(); i++) {
				String id = dataArray.getJSONObject(i).getString("id");
				if (id.equals(postID)) {
					JSONObject postComments = dataArray.getJSONObject(i).getJSONObject("comments");
					JSONArray commentsDataArray = postComments.getJSONArray("data");
					for (int j = 0; j < commentsDataArray.length(); j++) {
						String commentID = commentsDataArray.getJSONObject(j).getString("id");
						JSONObject from = commentsDataArray.getJSONObject(j).getJSONObject("from");
						String name = from.getString("name");
						String message = commentsDataArray.getJSONObject(j).getString("message");
						String timestamp = commentsDataArray.getJSONObject(j).getString("created_time");
						timestamp = timestamp.replace('T', ' ');
						timestamp = timestamp.substring(0, timestamp.length()-5);
				        
						allComments.add(new FacebookPost(commentID, name, message, timestamp));
					}
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (FacebookError e) {
			e.printStackTrace();
		}
	}

	private Facebook facebook = new Facebook("326103550760452");
	private AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
	private SharedPreferences mPrefs;
	private ListView postListView;
	private ArrayAdapter<FacebookPost> aa;
	private ArrayList<FacebookPost> allComments;
	private String id = "";
	private int numPosts = 10;

	private class PostRequestListener implements RequestListener {

		public void onComplete(final String response, final Object state) {
			getCommentsOnPost(id);
			runOnUiThread(new Runnable() {
				public void run() {
					getCommentsOnPost(id);
					setAdapter();
				}
			});
		}

		public void onIOException(IOException e, Object state) {

		}

		public void onFileNotFoundException(FileNotFoundException e,
				Object state) {

		}

		public void onMalformedURLException(MalformedURLException e,
				Object state) {

		}

		public void onFacebookError(FacebookError e, Object state) {

		}
	}
}